package com.mornstar.econvent.auth.handle;

import com.mornstar.common.constant.EconventConstant;
import com.mornstar.common.jackson.JsonUtil;
import com.mornstar.tool.api.R;
import com.mornstar.tool.api.ResultCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serializable;
import java.util.Objects;

/**
 * 认证失败处理类 返回未授权
 *
 * @author ruoyi
 */
@Slf4j
@Component
public class EcoAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
        R result = R.fail(ResultCode.UN_AUTHORIZED);
        response.setCharacterEncoding(EconventConstant.UTF_8);
        response.addHeader(EconventConstant.CONTENT_TYPE_NAME, MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            response.getWriter().write(Objects.requireNonNull(JsonUtil.toJson(result)));
        } catch (IOException ex) {
            log.error(ex.getMessage());
        }
    }
}
